package core;

import org.apache.commons.collections.MapUtils;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.*;

public class ClassPathXmlApplicationContext extends ApplicationContext {


	/**
	 * 5      * 构造方法，用来模拟spring的行为
	 * 6      * @param fileName
	 * 7
	 */
	public ClassPathXmlApplicationContext(String fileName) {

		this.readXml(fileName);
		this.instanceBeans();
	}

	/**
	 * 根据文件名读取xml的配置文件
	 *
	 * @param fileName Administer
	 *                 2013-8-26 下午11:09:16
	 */
	private void readXml(String fileName) {
		//创建一个读取器
		SAXReader saxReader = new SAXReader();
		Document document = null;
		try {
			//获取要读取的配置文件的路径
			URL xmlPath = this.getClass().getClassLoader().getResource(fileName);
			//读取文件内容
			document = saxReader.read(xmlPath);
			//获取xml中的根元素
			Element rootElement = document.getRootElement();
			Iterator iterator = rootElement.elementIterator();
			while (iterator.hasNext()) {
				Element element = (Element) iterator.next();
				String id = element.attributeValue("id");//获取bean的id属性值
				String clazz = element.attributeValue("class");//获取bean的class属性值
				BeanDefinition beanDefinition = new BeanDefinition(id, clazz);
				Iterator iterator1 = element.elementIterator();
				Map<String, String> stringBeanDefinitionMap = new HashMap<String, String>();
				while (iterator1.hasNext()) {
					Element next = (Element)iterator1.next();
					String name = next.attributeValue("name");
					String value = next.attributeValue("value");
					stringBeanDefinitionMap.put(name, value);
				}
				beanDefinition.setStringBeanDefinitionMap(stringBeanDefinitionMap);
				beanDefines.add(beanDefinition);
			}
		
		} catch (Exception e) {
			e.printStackTrace();
		}
	}



}
